<script setup lang='ts' name="admin-role">
import type { VxeGridProps, VxePagerEvents } from 'vxe-table'
import { useRouter } from 'vue-router'
import type { FormInstance } from 'element-plus'
import { SearchForm, SearchTable } from '@fl/components'
import { downloadFile } from '@fl/utils/fn'
import { cloneDeep } from 'lodash-es'
import { nextTick } from 'vue'
import { useSessionStorage } from '@vueuse/core'
import type { IState, Iform } from './types'
import { dialogTitle } from './types'
import { useJointStore } from '@fl/store/modules/joint'

import { addAreaRole, deleteAreaRole, getAreaRoleById, getAreaRoleList, getCardList, getCompanyByLoginUser, getCompanyCard, updateAreaRole } from '@fl/api/joint-api'
import { useUserStore } from '@fl/store/modules/user'
import { stat } from 'node:fs'

const jointCard = useJointStore().getJointCardInfo
console.log('🚀 ~ jointAppKey:', jointCard)
const router = useRouter()
const initialState: IState = {
    areaRoleName: '',
    areaId: '',
}
const cardList = ref<{name: string,appId: number,appKey: string}[]>([])
const areaList = ref([])
const state = ref(cloneDeep(initialState))
const statusList = [{
    label: '正常',
    value: '1',
}, {
    label: '停用',
    value: '0',
}]
const isEdit = ref(false)
const currentRoleId = ref('')
const selectedCard = ref({
    appKey: jointCard.appKey,
    appId: Number(jointCard.appId),
    appName: jointCard.appName,
})
const companyId = ref('')
const columns = ref([

    {
        label: '角色名称',
        prop: 'areaRoleName',
        valueType: 'copy',
    },
    {
        label: '负责区域',
        prop: 'areaId',
        options: [],
        valueType: 'select',
    },

])
const isLoading = ref(false)
const initialPage = {
    currentPage: 1,
    pageSize: 10,
    total: 0,
}
const tablePage = ref(cloneDeep(initialPage))
const gridOptions = reactive<VxeGridProps>({
    columns: [
        // { field: 'id', minWidth: 90, title: '序号' },
        { title: '序号', type: 'seq', width: 50 },
        { field: 'areaRoleName', minWidth: 100, title: '角色名称' },
        { field: 'areaName', minWidth: 120, title: '负责区域' },
        { field: 'businessName', minWidth: 80, title: '所属应用' },
        { field: 'status', minWidth: 80, slots: { default: 'status' }, title: '状态' },
        { field: 'creator', title: '创建人', width: 120 },
        { field: 'createTime', title: '创建时间', width: 200 },
        { fixed: 'right', minWidth: 120, slots: { default: 'operate' }, title: '操作' },
    ],
})
const list = ref([])
const initForm: Iform = {
    remark: '',
    appKey: jointCard.appKey,
    appId: Number(jointCard.appId),
    roleId: undefined,
    roleKey: undefined,
    areaRoleName: undefined,
    activeState: '1',
}
const formRef = ref()
const form = ref(cloneDeep(initForm))
const rules = {
    appId: [
        { message: '所属应用不能为空', required: true, trigger: 'blur' },
    ],
    // card: [
    //     { message: '所属应用不能为空', required: true, trigger: 'blur' },
    // ],
    areaRoleName: [
        { message: '角色名称不能为空', required: true, trigger: 'blur' },
    ],
    areaList: [
        { message: '所属区域不能为空', required: true, trigger: 'blur' },
    ],
    activeState: [
        { message: '状态不能为空', required: true, trigger: 'blur' },
    ],
}
const title = ref('新增角色')
const visible = ref(false)

const roleIds = ref('')
const startIdx = ref(0)
const userStore = useUserStore()
const isManager = ref<boolean>(userStore.getUserInfo?.userFlag === '2')

async function getListData() {
    isLoading.value = true
    const areaRes = await getAreaRoleList({
        ...state.value,
        pageNum: tablePage.value.currentPage,
        pageSize: tablePage.value.pageSize,
    })
    console.log('🚀 ~ getAreaRoleList ~ res:', areaRes)

    list.value = areaRes.records
    tablePage.value.total = areaRes.total

    isLoading.value = false

    companyId.value = window.sessionStorage.getItem('companyId') || ''
    const companyDetailStorage = useSessionStorage('companyDetail', null)
    let companyDetail = companyDetailStorage.value ? JSON.parse(companyDetailStorage.value) : null
    console.log('🚀 ~ getListData ~ companyDetail:', companyDetail)

    if (!companyId.value) {
        companyDetail = await getCompanyByLoginUser()
        companyId.value = companyDetail.id
        useSessionStorage('companyId', companyDetail.id)
        useSessionStorage('companyDetail', companyDetail)
    }
    areaList.value = companyDetail?.companyAreaAssociationList
    columns.value.forEach((item) => {
        if (item.prop === 'areaId') {
            item.options = companyDetail?.companyAreaAssociationList?.map(companyArea => ({
                // 省市区
                label: `${companyArea.provinceName},${companyArea.cityName},${companyArea.areaName}`,
                value: companyArea.id,
            }))
        }
    })
    const res = await getCompanyCard()
    cardList.value = [{ name: jointCard.appName, appKey: jointCard.appKey, appId: Number(jointCard.appId) }, ...res.map(card => ({ name: card.cardName, appKey: card.appKey, appId: Number(card.cardId) }))] || []

      console.log('🚀 ~ getCardList ~ :', cardList.value)
}

getListData()

//
const { mutateAsync: runGetAreaRoleById } = useMutation({
    mutationFn: (data: any) => getAreaRoleById(data),
    onSuccess: async (data) => {
        if (data) {
            console.log('🚀 ~ getAreaRoleById ~ data:', data)
            const { id, appId, areaRoleName, areaList, activeState } = data
            changeApp(Number(appId))
            form.value = {
                id,
                appId: Number(appId),
                areaRoleName,
                areaList,
                activeState,
            }
        }
    },
})

function setStatus(row) {
    // const { roleId, status } = row
    // roleStatus({
    //     roleId,
    //     status,
    // }).then((res) => {
    //     console.log(2333, res)
    //     ElMessage.success('操作成功')
    //     getListData()
    // }).catch(() => {
    //     getListData()
    // })
}

function changeApp(value) {
    console.log('🚀 ~ changeApp ~ value:', value)
    // 通过value获取到选中的card
    const card = cardList.value.find(item => item.appId === value)
    if (!card)
        return
    console.log('🚀 ~ changeApp ~ selectedItem:', card)
    selectedCard.value = card

    // form.value.appKey = selectedItem.appKey
}

const handlePageChange: VxePagerEvents.PageChange = ({ currentPage, pageSize }) => {
    tablePage.value.currentPage = currentPage
    tablePage.value.pageSize = pageSize
    startIdx.value = (currentPage - 1) * pageSize
    getListData()
}

function resetSearch() {
    state.value = cloneDeep(initialState)
    getListData()
}

function submitSearch(values) {
    if (values) {
        console.log('🚀 ~ submitSearch ~ values:', values)

        const { areaRoleName, areaId } = values

        state.value = {
            areaRoleName,
            areaId,
        }
        tablePage.value.currentPage = 1
        getListData()
    }
}

// 打开弹窗
async function showDialog(type, row) {
    title.value = type
    const { id, appId, areaRoleName, areaList, activeState } = row
    switch (type) {
        case dialogTitle.ADD:
            form.value = cloneDeep(initForm)
            // const res = await getAddRoleTreeData()
            // menuOptions.value = res
            visible.value = true
            isEdit.value = false
            break
        case dialogTitle.EDIT:
            isEdit.value = true
            currentRoleId.value = id
            runGetAreaRoleById(id)

            // const menuTreeData = await getEditRoleTreeData(row.roleId)
            // menuOptions.value = menuTreeData.menus
            // form.value.menuIds = menuTreeData.checkedKeys
            visible.value = true
            // nextTick(() => {
            //     menuTreeData.checkedKeys.forEach((v) => {
            //         menuTreeRef.value.setChecked(v, true, false)
            //     })
            // })
            break
    }
}

// 取消按钮
function cancel() {
    visible.value = false
}

// 提交按钮
function submitForm(formEl: FormInstance | undefined) {
    if (!formEl)
        return
    formEl.validate((valid) => {
        if (valid) {
            const { areaList, areaRoleName, activeState } = form.value
            const params = {
                areaList,
                areaRoleName,
                activeState,
                businessId: selectedCard.value?.id,
                appId: selectedCard.value?.appId,
                businessName: selectedCard.value.appName,
                companyId: companyId.value,
            }
            console.log('🚀 ~ formEl.validate ~ params:', selectedCard.value, params)

            switch (title.value) {
                case dialogTitle.ADD:

                    addAreaRole(params).then(() => {
                        getListData()
                        ElMessage.success('新增成功')
                    })
                    break
                case dialogTitle.EDIT:

                    updateAreaRole({ ...params, id: currentRoleId.value }).then(() => {
                        getListData()
                        ElMessage.success('修改成功')
                    })
                    break
            }
            visible.value = false
        }
    })
}

function delRole(row) {
    ElMessageBox.confirm(
        row?.id ? `您确定要删除角色『${row.areaRoleName}』吗？` : '您确定要所勾选的角色吗？',
        row?.id ? '删除' : '批量删除',
        {
            cancelButtonText: '取消',
            confirmButtonText: '删除',
            type: 'warning',
        },
    )
        .then(() => {
            const params = row?.id ?? roleIds.value
            deleteAreaRole([params]).then(() => {
                ElMessage.success('删除成功')
                getListData()
            }).catch(() => {
                ElMessage.error('接口请求失败')
            })
        }).catch(() => {
            ElMessage({
                message: '取消删除',
                type: 'info',
            })
        })
}

function checkboxChange(values) {
    const ids = values.records.map(item => item.roleId)
    roleIds.value = ids.join()
}

function toPage(row) {
    router.push({ name: 'role-auth-user', params: { id: row.roleId } })
}

/**
 * methods end
*/
</script>

<template>
    <div class="sys-role">
        <ElCard class="mb-20"
                shadow="never"
        >
            <SearchForm v-bind="state"
                        :columns="columns"
                        submit-text="搜索"
                        @reset="resetSearch"
                        @submit="submitSearch"
            />
        </ElCard>

        <ElCard shadow="never">
            <SearchTable v-bind="gridOptions"
                         v-model:pager="tablePage"
                         :loading="isLoading"
                         :seq-config="{ startIndex: startIdx }"
                         :data="list"
                         @page-change="handlePageChange"
                         @checkbox-change="checkboxChange"
            >
                <template #toolbar_buttons>
                    <el-button v-if="isManager"
                               plain
                               type="primary"
                               @click="showDialog(dialogTitle.ADD, {})"
                    >
                        新增
                    </el-button>
                </template>

                <template #time="{ row }">
                    {{ row.startTime }} ~ {{ row.endTime }}
                </template>

                <template #status="{ row }">
                    <!-- <el-switch v-model="row.status"
                               active-value="0"
                               inactive-value="1"
                               @change="setStatus(row)"
                    /> -->
                    {{ Number(row.activeState) ? '正常' : '停用' }}
                </template>

                <template #operate="{ row }">
                    <!-- roleId为1是超级管理员 -->
                    <div v-if="row.roleId !== 1"
                         class="operate-btns"
                    >
                        <el-button type="primary"
                                   text
                                   @click="showDialog(dialogTitle.EDIT, row)"
                        >
                            编辑
                        </el-button>

                        <!-- <el-button type="primary"
                                   text
                                   @click="toPage(row)"
                        >
                            分配用户
                        </el-button> -->

                        <el-button type="default"
                                   text
                                   @click="delRole(row)"
                        >
                            删除
                        </el-button>
                    </div>
                </template>
            </SearchTable>
        </ElCard>
        <!-- 添加或修改角色配置对话框 -->
        <el-dialog v-model="visible"
                   :title="title"
                   width="666px"
        >
            <el-form ref="formRef"
                     class="dialog-form"
                     :model="form"
                     :rules="rules"
                     label-width="100px"
                     label-position="right"
            >
                <el-form-item label="所属应用"
                              prop="appId"
                >
                    <el-select v-model="form.appId"
                               value-key="id"
                               placeholder="请选择所属应用"
                               @change="changeApp"
                    >
                        <el-option v-for="item in cardList"
                                   :key="item.appId"
                                   :label="item.name"
                                   :value="item.appId"
                        />
                    </el-select>
                </el-form-item>

                <el-form-item label="角色名称"
                              prop="areaRoleName"
                >
                    <el-input v-model="form.areaRoleName"
                              placeholder="请输入角色名称"
                    />
                </el-form-item>

                <el-form-item label="分配区域"
                              prop="areaList"
                >
                    <el-select v-model="form.areaList"
                               value-key="id"
                               multiple
                               placeholder="请选择区域"
                    >
                        <el-option v-for="item in areaList"
                                   :key="item.id"
                                   :label="`${item.provinceName},${item.cityName},${item.areaName}`"
                                   :value="item"
                        />
                    </el-select>
                </el-form-item>

                <el-form-item label="状态"
                              prop="activeState"
                >
                    <el-radio-group v-model="form.activeState">
                        <el-radio v-for="dict in statusList"
                                  :key="dict.value"
                                  :value="dict.value"
                        >
                            {{ dict.label }}
                        </el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-form>

            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary"
                               @click="submitForm(formRef)"
                    >
                        确 定
                    </el-button>

                    <el-button @click="cancel">
                        取 消
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<style lang="scss" scoped>
.sys-role {
    .dialog-form {
        height: calc(70vh - 200px);
        overflow-y: auto;
    }

    .dialog-footer {
        display: flex;
        justify-content: end;
        margin-top: 30px;
    }

    :deep(.operate-btns .el-button) {
        margin: 0;
        padding: 6px;
    }
}
</style>
